package com.example.websocket.websocket.socket;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class SelectorClient {

    static int cnum = 100;

    public static void main(String[] args) {
        Thread thread = new Thread(new MyTestThread("test1"));
        Thread thread1 = new Thread(new MyTestThread("test2"));
        Thread thread2 = new Thread(new MyTestThread("test3"));
        thread.start();
        thread1.start();
        thread2.start();
    }

    public static class MyTestThread implements Runnable {

        private String name;

        public MyTestThread() {
        }

        public MyTestThread(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            send();
        }

        public void send() {
            try {
                SocketChannel socketChannel = SocketChannel.open();
                socketChannel.connect(new InetSocketAddress("localhost", 8081));
                while (true) {
                    ByteBuffer buffer = ByteBuffer.wrap((name + ":购买了一件商品，剩余" + cnum).getBytes());
                    socketChannel.write(buffer);
                    ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                    int num;
                    if ((num = socketChannel.read(readBuffer)) > 0) {
                        readBuffer.flip();
                        byte[] result = new byte[num];
                        readBuffer.get(result);
                        String demo = new String(result, "UTF-8");
                        System.out.println("返回值：" + demo);
                        if (demo.contains("不足")) {
                            Thread.sleep(1000000);
                        } else {
//                            cnum = Integer.parseInt(demo);
                            Thread.sleep(1000);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
